<template>
    <div>
        <el-form ref="userFormRef" :model="userForm" status-icon :rules="rules" label-width="120px" class="userForm">
        <div class="form">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="userForm.username" type="text" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="userForm.password" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
                <el-input v-model="userForm.nickname" type="text" autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="userForm.email" type="email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="userForm.phone" type="text" autocomplete="off" />
            </el-form-item>
        </div>
        <div>
            <!-- auto-upload 自动上传 -->
            <el-upload class="avatar-uploader" ref="uploadAvatar" action="http://120.76.247.5:2001/api/upload/avatar"
                name="avatar" :data="{userid:regUserID}" 
                :headers="{Authorization:store.state.userStore.Authorization}" 
                :auto-upload="false"
                :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                :on-change="handleChange">
                <img v-if="imageUrl" width="100" :src="imageUrl" class="avatar" />
                <el-avatar v-else shape="square" :size="150" src="https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png" />
            </el-upload>
        </div>
    </el-form>
    <div class="btn">
        <el-button type="primary" @click="addUser(userFormRef)">添加用户</el-button>
    </div>
    </div>
    

</template>
  
<script setup>
import http from '@/utils/http.js'
import { reactive, ref } from 'vue'
import {useStore} from 'vuex'
import {useRouter} from 'vue-router'
let store=useStore();//this.$store
let router=useRouter();//this.$router
let userFormRef = ref(null);
let userForm = reactive({
    username: "",
    password: "",
    nickname: "",
    email: "",
    phone: ""
});
let regUserID=ref(0);
let uploadAvatar=ref(null);//ref关联el-upload组件
let rules = reactive({
    username: [
        { required: true, message: "用户名不能为空", trigger: "blur" },
        { min: 3, max: 20, message: "用户名长度3-20字符", trigger: "blur" },
    ],
    password: [
        { required: true, message: "密码不能为空", trigger: "blur" },
        { min: 3, max: 20, message: "密码长度3-20字符", trigger: "blur" },
    ],
    email: [
        { required: true, message: "用户名不能为空", trigger: "blur" },
        { type: "email", message: "邮箱格式不正确", trigger: "blur" },
    ],
    phone: [
        { required: true, message: "电话号码不能为空", trigger: "blur" },
        { pattern: /^1[3456789]\d{9}$/, message: "电话号码格式不正确", trigger: "blur" },
    ]
})
let imageUrl=ref("");//存储上传文件的链接地址
let handleAvatarSuccess=(result)=>{
    // console.log("result====>",result);
    // if(result.status==200){//上传成功把头像地址写入userForm对象
    //     userForm.avatar=result.data.avatar;
    // }
}
let beforeAvatarUpload=(file)=>{ //File文件对象 可以转化为blob二进制显示
    // console.log('beforeFile',file)
    if(file.type!=="image/jpeg"){
        ElMessage({
            type:"error",
            message:"只能上传jpg图片"
        });
        return false;
    }
    if(file.size /1024 /1024 >1){
        ElMessage({
            type:"error",
            message:"只能上传最大1MB的图片"
        });
        return false;
    }
    // imageUrl.value=URL.createObjectURL(file);
    return true;
}
let handleChange=(file)=>{
    // console.log('handleChange',file)
    imageUrl.value=URL.createObjectURL(file.raw);
}
let addUser = (userFormRef) => {
    userFormRef.validate(async (ispass) => {
        if (ispass) {
            let re = await http.post("/user/reg", userForm);
            // console.log("添加结果===>",re);
            ElMessage({
                type: "success",
                message: "用户添加成功!"
            })
            regUserID.value=re.id;//把注册用户的id存起来
            uploadAvatar.value.submit();//手动提交上传组件 上传文件
            router.push("list");
            // let f=new FormData();//创建一个表单对象 <form><input name="username" value="zhaojiaxin"></form>
                // f.append("username","zhaojiaxin");
                // f.append("avatar",File)
            // axios.post("xxxx",FormData);
        } else {
            console.log("验证未通过");
        }
    });
}
</script>
  
<style lang="scss" scoped>
.userForm {
    width: 500px;
    margin: 0 auto;
    text-align: center;
    display: flex;
    justify-content: space-between;
    div{
        &.form{
            width:300px;
        }
    }
}
.btn{
    text-align: center;
}
</style>